package com.weaver.seconddev.api.tl.gr_api;

/**
 * E9原始类路径:com.weaver.seconddev.api.tl.gr_api.GrService
 * JAVA替换说明文档:https://ncnb71xwgeda.feishu.cn/wiki/JLsjwxK8xiHuPIkdu0Dc27Rlnaf?from=from_copylink
 */
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.verupgrade.conn.CONN_TYPE;
import java.lang.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.file.Prop;
import com.weaver.verupgrade.general.BaseBean;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;

@org.springframework.stereotype.Service("tl_gr_api_GrService")
public class GrService {


    public static final org.slf4j.Logger logger_43c2ede6 = LoggerFactory.getLogger(GrService.class);


    private static final Properties prop = Prop.loadTemplateProp(System.getenv("ENV") + File.separatorChar + "gr_interface_url");

    // GR申请流程-NBS/NPR 表名称
    private static final String nbsApplyWorkflowTable = prop.getProperty("nbs_apply_workflow_table");

    // GR申请流程-NBS/NPR 明细表名称
    private static final String nbsApplyWorkflowTableDetail = prop.getProperty("nbs_apply_workflow_table_detail");

    // SC GCN_GR申请流程-NBS/NPR 表名称
    private static final String scApplyWorkflowTable = prop.getProperty("sc_apply_workflow_table");

    // SC GCN_GR申请流程 表名称
    private static final String scApplyWorkflowTableDetail = prop.getProperty("sc_apply_workflow_table_detail");


    //
    @Resource(name = "tl_service_EcologyCommonService2")
    private EcologyCommonService2 ecologyCommonService2;
    /**
     * 上传GR
     */
    public JSONObject postGR(JSONObject jsonObject) {
        logger_43c2ede6.info(">>>GrService postGR PostGRBean => " + jsonObject);
        String jsonParam = JSONUtil.toJsonStr(jsonObject);
        //String data = EcologyCommonService2.callESBInterface("postGR", jsonParam);
        String data = ecologyCommonService2.callESBInterface("100613275897086096", jsonParam);
        if (StringUtils.isBlank(data)) {
            throw new RuntimeException("error postGR");
        }
        JSONObject retJsonObject = JSON.parseObject(data);
        if (retJsonObject.getJSONObject("message") != null && "E".equals(retJsonObject.getJSONObject("message").getString("messageType"))) {
            throw new RuntimeException(retJsonObject.getJSONObject("message").getString("details"));
        }
        logger_43c2ede6.info(String.valueOf(">>>GrService postGR retRes => " + data));
        return retJsonObject;
    }

    /**
     * 取消GR
     */
    public JSONObject reverseGR(JSONObject jsonObject) {
        logger_43c2ede6.info(">>>GrService postGR reverseGR param => " + jsonObject);
        String jsonParam = JSONUtil.toJsonStr(jsonObject);
        String data = ecologyCommonService2.callESBInterface("100613275897086100", jsonParam);
        if (StringUtils.isBlank(data)) {
            throw new RuntimeException("error postGR");
        }
        JSONObject retJsonObject = JSON.parseObject(data);
        if (retJsonObject.getJSONObject("message") != null && "E".equals(retJsonObject.getJSONObject("message").getString("messageType"))) {
            throw new RuntimeException(retJsonObject.getJSONObject("message").getString("details"));
        }
        logger_43c2ede6.info(String.valueOf(">>>GrService postGR reverseGR return => " + data));
        return retJsonObject;
    }

    /**
     * 获取PO数据
     * @param poNumber PO号
     * @param items ITEMS /分割
     */
    public Map<String, Object> getPoData(String poNumber, String items) {
        logger_43c2ede6.info(String.valueOf(">>>GrService getPoData poNumber = " + poNumber + ",items = " + items));
        String[] itemArr = new String[] {};
        if (StringUtils.isNotBlank(items)) {
            itemArr = Arrays.stream(items.split("/")).toArray(String[]::new);
        }
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("poNumber", poNumber);
        paraMap.put("exportJson", "X");
        paraMap.put("items", itemArr);
        String jsonParam = JSONUtil.toJsonStr(paraMap);
        String data = ecologyCommonService2.callESBInterface("100613275897086092", jsonParam);
        if (StringUtils.isBlank(data)) {
            throw new RuntimeException("error getPoData");
        }
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.getString("errorMessage") != null) {
            throw new RuntimeException(jsonObject.getString("errorMessage"));
        }
        JSONArray poItemsArr = jsonObject.getJSONArray("po_items");
        JSONArray accountAssignmentArr = jsonObject.getJSONArray("account_assignment");
        JSONArray historyArr = jsonObject.getJSONArray("gr_history");
        List<Map<String, Object>> itemList = JSON.toJavaObject(poItemsArr, List.class);
        List<Map<String, Object>> assignList = JSON.toJavaObject(accountAssignmentArr, List.class);
        List<Map<String, Object>> grHistoryList = JSON.toJavaObject(historyArr, List.class);
        // 查询po号的总金额
        String bigDecimal = getTotalNetPrice(poNumber);
        // 过滤出未删除的item
        itemList = itemList.stream().filter(item -> !"X".equalsIgnoreCase(String.valueOf(item.get("delete_ind")))).collect(Collectors.toList());
        Optional.ofNullable(itemList).orElse(new ArrayList<>()).stream().forEach(item -> {
            String poItem = String.valueOf(item.get("po_item"));
            // 将accountAssignmentArr中的数据合并到poItemsArr中
            Optional.ofNullable(assignList).orElse(new ArrayList<>()).forEach(assign -> {
                if (poItem.equals(String.valueOf(assign.get("po_item")))) {
                    item.putAll(assign);
                }
            });
        });
        // 赋值dataMap
        List<Map<String, Object>> dataList = new ArrayList<>();
        Optional.ofNullable(itemList).orElse(new ArrayList<>()).forEach(tempItem -> {
            HashMap<String, Object> dataMap = new HashMap<>();
            dataMap.put("item", tempItem.get("po_item"));
            dataMap.put("material", tempItem.get("material"));
            dataMap.put("cost_type", tempItem.get("acctasscat"));
            dataMap.put("material_description", tempItem.get("short_text"));
            dataMap.put("quantity", tempItem.get("quantity"));
            dataMap.put("received_quantity", tempItem.get("received_quantity"));
            dataMap.put("unit", tempItem.getOrDefault("po_unit", ""));
            dataMap.put("internal_order", tempItem.getOrDefault("orderid", ""));
            dataMap.put("cost_center", tempItem.getOrDefault("costcenter", ""));
            dataMap.put("network", tempItem.getOrDefault("network", ""));
            dataMap.put("fixed_asset_No", tempItem.getOrDefault("asset_no", ""));
            dataMap.put("net_price", tempItem.getOrDefault("net_price", ""));
            // 过滤出GR history中item的 gr号和grYear
            Optional.ofNullable(grHistoryList).orElse(new ArrayList<>()).forEach(history -> {
                if (tempItem.get("po_item").equals(history.get("po_item"))) {
                    // 也可能history没匹配到 最后没有这两个字段
                    dataMap.put("mat_doc", history.getOrDefault("mat_doc", ""));
                    dataMap.put("doc_year", history.getOrDefault("doc_year", ""));
                    dataMap.put("matdoc_itm", history.getOrDefault("matdoc_itm", ""));
                }
            });
            dataList.add(dataMap);
        });
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("dataList", dataList);
        dataMap.put("totalSapPrice", bigDecimal);
        return dataMap;
    }

    /**
     * 根据PO号获取netPrice总金额
     * @param poNumber 号
     */
    public String getTotalNetPrice(String poNumber) {
        logger_43c2ede6.info(String.valueOf(">>>prepare getPoData total netPrice poNumber = " + poNumber));
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("poNumber", poNumber);
        paraMap.put("exportJson", "X");
        paraMap.put("items", new String[] {});
        String jsonParam = JSONUtil.toJsonStr(paraMap);
        String data = ecologyCommonService2.callESBInterface("100613275897086092", jsonParam);
        if (StringUtils.isBlank(data)) {
            throw new RuntimeException("error getPoData");
        }
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.getString("errorMessage") != null) {
            throw new RuntimeException(jsonObject.getString("errorMessage"));
        }
        JSONArray poItemsArr = jsonObject.getJSONArray("po_items");
        JSONArray accountAssignmentArr = jsonObject.getJSONArray("account_assignment");
        List<Map<String, Object>> itemList = JSON.toJavaObject(poItemsArr, List.class);
        List<Map<String, Object>> assignList = JSON.toJavaObject(accountAssignmentArr, List.class);
        AtomicReference<BigDecimal> bigDecimal = new AtomicReference<>(BigDecimal.ZERO);
        Optional.ofNullable(itemList).orElse(new ArrayList<>()).forEach(tempItem -> {
            String poItem = String.valueOf(tempItem.get("po_item"));
            // 将accountAssignmentArr中的数据合并到poItemsArr中
            Optional.ofNullable(assignList).orElse(new ArrayList<>()).forEach(assign -> {
                if (poItem.equals(String.valueOf(assign.get("po_item")))) {
                    tempItem.putAll(assign);
                }
            });
            // 金额相加
            if (tempItem.get("net_price") != null && !"".equals(tempItem.get("net_price"))) {
                try {
                    BigDecimal netPrice = bigDecimal.get().add(new BigDecimal(String.valueOf(tempItem.get("net_price"))));
                    bigDecimal.set(netPrice);
                } catch (Exception e) {
                    logger_43c2ede6.info(String.valueOf("net_price calculate exception!! current net_price is " + tempItem.get("net_price")));
                }
            }
        });
        return bigDecimal.toString();
    }

    /**
     * 获取PO数据 (SC GCN_GR取消流程)
     * @param poNumber PO号
     * @param items ITEMS /分割
     */
    public Map<String, Object> getScCancelPoData(String poNumber, String items) {
        logger_43c2ede6.info(String.valueOf(">>>GrService getScCancelPoData poNumber = " + poNumber + ",items = " + items));
        String[] itemArr = new String[] {};
        if (StringUtils.isNotBlank(items)) {
            itemArr = Arrays.stream(items.split("/")).toArray(String[]::new);
        }
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("poNumber", poNumber);
        paraMap.put("exportJson", "X");
        paraMap.put("items", itemArr);
        String jsonParam = JSONUtil.toJsonStr(paraMap);
        String data = ecologyCommonService2.callESBInterface("100613275897086092", jsonParam);
        if (StringUtils.isBlank(data)) {
            throw new RuntimeException("error getPoData");
        }
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.getString("errorMessage") != null) {
            throw new RuntimeException(jsonObject.getString("errorMessage"));
        }
        JSONArray poItemsArr = jsonObject.getJSONArray("po_items");
        JSONArray accountAssignmentArr = jsonObject.getJSONArray("account_assignment");
        JSONArray historyArr = jsonObject.getJSONArray("gr_history");
        List<Map<String, Object>> itemList = JSON.toJavaObject(poItemsArr, List.class);
        List<Map<String, Object>> assignList = JSON.toJavaObject(accountAssignmentArr, List.class);
        List<Map<String, Object>> grHistoryList = JSON.toJavaObject(historyArr, List.class);
        // 查询po号的总金额
        String bigDecimal = getTotalNetPrice(poNumber);
        Optional.ofNullable(itemList).orElse(new ArrayList<>()).forEach(item -> {
            String poItem = String.valueOf(item.get("po_item"));
            // 将accountAssignmentArr中的数据合并到poItemsArr中
            Optional.ofNullable(assignList).orElse(new ArrayList<>()).forEach(assign -> {
                if (poItem.equals(String.valueOf(assign.get("po_item")))) {
                    item.putAll(assign);
                }
            });
        });
        // 赋值dataMap
        List<Map<String, Object>> dataList = new ArrayList<>();
        RecordSet recordSet = I18nContextUtil.getBean(RecordSet.class);
        Optional.ofNullable(itemList).orElse(new ArrayList<>()).forEach(tempItem -> {
            HashMap<String, Object> dataMap = new HashMap<>();
            dataMap.put("item", tempItem.get("po_item"));
            dataMap.put("material", tempItem.get("material"));
            dataMap.put("cost_type", tempItem.get("acctasscat"));
            dataMap.put("material_description", tempItem.get("short_text"));
            dataMap.put("quantity", tempItem.get("quantity"));
            dataMap.put("received_quantity", tempItem.get("received_quantity"));
            dataMap.put("unit", tempItem.getOrDefault("po_unit", ""));
            dataMap.put("internal_order", tempItem.getOrDefault("orderid", ""));
            dataMap.put("cost_center", tempItem.getOrDefault("costcenter", ""));
            dataMap.put("network", tempItem.getOrDefault("network", ""));
            dataMap.put("fixed_asset_No", tempItem.getOrDefault("asset_no", ""));
            dataMap.put("net_price", tempItem.getOrDefault("net_price", ""));
            // 过滤出GR history中item的 gr号和grYear
            Optional.ofNullable(grHistoryList).orElse(new ArrayList<>()).forEach(history -> {
                // S代表已GR的 H代表已取消GR的
                if (!"S".equals(history.get("db_cr_ind"))) {
                    return;
                }
                if (!tempItem.get("po_item").equals(history.get("po_item"))) {
                    return;
                }
                // 从BPM里匹配这三个字段
                String querySQL = "select count(*) as ctn from " + scApplyWorkflowTableDetail + " where item = '" + tempItem.get("po_item") + "' and mainid = " + "(select id from " + scApplyWorkflowTable + " where document_number = '" + history.get("mat_doc") + "' and gr_year = '" + history.get("doc_year") + "' limit 1) and gc_check = 0";
                logger_43c2ede6.info(String.valueOf("querySQL => " + querySQL));
                String poolname = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                recordSet.executeQuery(querySQL, poolname);
                if (recordSet.next() && recordSet.getInt("ctn") != 0) {
                    // 也可能history没匹配到 最后没有这两个字段
                    dataMap.put("mat_doc", history.getOrDefault("mat_doc", ""));
                    dataMap.put("doc_year", history.getOrDefault("doc_year", ""));
                    dataMap.put("matdoc_itm", history.getOrDefault("matdoc_itm", ""));
                }
            });
            dataList.add(dataMap);
        });
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("dataList", dataList);
        dataMap.put("totalSapPrice", bigDecimal);
        return dataMap;
    }

    /**
     * 获取PO数据 (nbs GR取消流程中使用)
     * @param poNumber PO号
     * @param items ITEMS /分割
     */
    public Map<String, Object> getNbsCancelPoData(String poNumber, String items) {
        logger_43c2ede6.info(String.valueOf(">>>GrService getNbsCancelPoData poNumber = " + poNumber + ",items = " + items));
        String[] itemArr = new String[] {};
        if (StringUtils.isNotBlank(items)) {
            itemArr = Arrays.stream(items.split("/")).toArray(String[]::new);
        }
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("poNumber", poNumber);
        paraMap.put("exportJson", "X");
        paraMap.put("items", itemArr);
        String jsonParam = JSONUtil.toJsonStr(paraMap);
        String data = ecologyCommonService2.callESBInterface("100613275897086092", jsonParam);
        if (StringUtils.isBlank(data)) {
            throw new RuntimeException("error getPoData");
        }
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.getString("errorMessage") != null) {
            throw new RuntimeException(jsonObject.getString("errorMessage"));
        }
        JSONArray poItemsArr = jsonObject.getJSONArray("po_items");
        JSONArray accountAssignmentArr = jsonObject.getJSONArray("account_assignment");
        JSONArray historyArr = jsonObject.getJSONArray("gr_history");
        List<Map<String, Object>> itemList = JSON.toJavaObject(poItemsArr, List.class);
        List<Map<String, Object>> assignList = JSON.toJavaObject(accountAssignmentArr, List.class);
        List<Map<String, Object>> grHistoryList = JSON.toJavaObject(historyArr, List.class);
        // 查询po号的总金额
        String bigDecimal = getTotalNetPrice(poNumber);
        Optional.ofNullable(itemList).orElse(new ArrayList<>()).forEach(item -> {
            String poItem = String.valueOf(item.get("po_item"));
            // 将accountAssignmentArr中的数据合并到poItemsArr中
            Optional.ofNullable(assignList).orElse(new ArrayList<>()).forEach(assign -> {
                if (poItem.equals(String.valueOf(assign.get("po_item")))) {
                    item.putAll(assign);
                }
            });
        });
        // 赋值dataMap
        List<Map<String, Object>> dataList = new ArrayList<>();
        RecordSet recordSet = I18nContextUtil.getBean(RecordSet.class);
        Optional.ofNullable(itemList).orElse(new ArrayList<>()).forEach(tempItem -> {
            HashMap<String, Object> dataMap = new HashMap<>();
            dataMap.put("item", tempItem.get("po_item"));
            dataMap.put("material", tempItem.get("material"));
            dataMap.put("cost_type", tempItem.get("acctasscat"));
            dataMap.put("material_description", tempItem.get("short_text"));
            dataMap.put("quantity", tempItem.get("quantity"));
            dataMap.put("received_quantity", tempItem.get("received_quantity"));
            dataMap.put("unit", tempItem.getOrDefault("po_unit", ""));
            dataMap.put("internal_order", tempItem.getOrDefault("orderid", ""));
            dataMap.put("cost_center", tempItem.getOrDefault("costcenter", ""));
            dataMap.put("network", tempItem.getOrDefault("network", ""));
            dataMap.put("fixed_asset_No", tempItem.getOrDefault("asset_no", ""));
            dataMap.put("net_price", tempItem.getOrDefault("net_price", ""));
            // 过滤出GR history中item的 gr号和grYear
            Optional.ofNullable(grHistoryList).orElse(new ArrayList<>()).forEach(history -> {
                // S代表已GR的 H代表已取消GR的
                if (!"S".equals(history.get("db_cr_ind"))) {
                    return;
                }
                if (!tempItem.get("po_item").equals(history.get("po_item"))) {
                    return;
                }
                // 从BPM里匹配这三个字段
                String querySQL = "select count(*) as ctn from " + nbsApplyWorkflowTableDetail + " where item = '" + tempItem.get("po_item") + "' and mainid = " + "(select id from " + nbsApplyWorkflowTable + " where document_number = '" + history.get("mat_doc") + "' and gr_year = '" + history.get("doc_year") + "' limit 1) and gc_check = 0";
                logger_43c2ede6.info(String.valueOf("querySQL => " + querySQL));
                String poolname_hf = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                recordSet.executeQuery(querySQL, poolname_hf);
                if (recordSet.next() && recordSet.getInt("ctn") != 0) {
                    // 也可能history没匹配到 最后没有这两个字段
                    dataMap.put("mat_doc", history.getOrDefault("mat_doc", ""));
                    dataMap.put("doc_year", history.getOrDefault("doc_year", ""));
                    dataMap.put("matdoc_itm", history.getOrDefault("matdoc_itm", ""));
                }
            });
            dataList.add(dataMap);
        });
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("dataList", dataList);
        dataMap.put("totalSapPrice", bigDecimal);
        return dataMap;
    }
}
